const Base = require('./base.js');

module.exports = class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async listAdminAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const model = this.model('admin_list');
    const query = this.get();

    delete query.page;
    delete query.size;

    if (query.name) {
      query.name = ['like', `%${query.name}%`];
    }

    if (query.nickname) {
      query.nickname = ['like', `%${query.nickname}%`];
    }

    const data = await model
      .where(query)
      .page(page, size)
      .countSelect();
    return this.success(data);
  }

  async putAction() {
    const values = this.post();
    const id = this.post('id');
    const model = this.model('admin_list');

    if (id > 0) {
      await model.where({ id: id }).update(values);
    } else {
      delete values.id;

      const hasUser = await model.where({ username: values.username }).find();
      if (!think.isEmpty(hasUser)) {
        return this.fail(400, '用户名被占用');
      }
      values.create_time = ['exp', 'CURRENT_TIMESTAMP()'];
      await model.add({
        password: 'e10adc3949ba59abbe56e057f20f883e',
        username: values.username,
        create_time: ['exp', 'CURRENT_TIMESTAMP()'],
        name: values.name,
        phone: values.phone,
        role_type: values.role_type,
      });
    }
    return this.success(values);
  }

  async resetPasswordAction() {
    const id = this.get('id');
    const model = this.model('admin_list');
    const data = await model.where({ id: id }).update({
      password: 'e10adc3949ba59abbe56e057f20f883e',
    });
    return this.success(data);
  }

  async updateAction() {
    const id = this.post('id');
    const status = this.post('status');
    if (id === 1) {
      return this.fail(401, '此用户不能编辑');
    }
    const model = this.model('admin_list');
    await model.where({ id: id }).update({
      status: status,
    });
    return this.success();
  }

  async deleteSysAction() {
    const id = this.get('id');
    if (id === '1') {
      return this.fail(400, '这个不能删！');
    }
    await this.model('admin_list')
      .where({ id: id })
      .limit(1)
      .delete();
    // TODO 删除图片

    return this.success();
  }
};
